package com.giggle.mybatis.helper;

import com.alibaba.druid.pool.DruidDataSource;
import com.giggle.mybatis.config.DataSourceProperties;
import com.google.common.collect.Lists;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.sql.SQLException;

/**
 * @author guozichen
 * @ClassName:
 * @Description: (这里用一句话描述累的作用)
 * @date 2020/9/1 18:42
 */
public class DruidDataSourceHelper {

    private static final Logger logger = LoggerFactory.getLogger(DruidDataSourceHelper.class);

    public DruidDataSourceHelper() {
    }

    public static DruidDataSource createDruidDataSource(DataSourceProperties dataSourceConfigVo, String connectionProperties) throws SQLException {
        if (logger.isDebugEnabled()) {
            logger.debug("Set data source as {}", dataSourceConfigVo);
        }

        if (null != dataSourceConfigVo && !StringUtils.isBlank(dataSourceConfigVo.getUrl())) {
            DruidDataSource dataSource = new DruidDataSource();
            dataSource.setUrl(dataSourceConfigVo.getUrl());
            dataSource.setUsername(dataSourceConfigVo.getUserName());
            dataSource.setPassword(dataSourceConfigVo.getUserPassword());
            dataSource.setInitialSize(dataSourceConfigVo.getInitialSize());
            dataSource.setMaxActive(dataSourceConfigVo.getMaxActive());
            dataSource.setMinIdle(dataSourceConfigVo.getMinIdle());
            dataSource.setMaxWait((long)dataSourceConfigVo.getMaxWait());
            dataSource.setValidationQuery(dataSourceConfigVo.getValidationQuery());
            setDefaultProperty(dataSource);
            String filters = dataSourceConfigVo.getFilters();
            dataSource.setFilters("mergeStat");
            if (StringUtils.isNotBlank(filters)) {
                dataSource.setFilters("mergeStat," + filters);
            }

            dataSource.setConnectionInitSqls(Lists.newArrayList(new String[]{"set names utf8mb4;"}));
            if (StringUtils.isNotBlank(connectionProperties)) {
                dataSource.setConnectionProperties(connectionProperties);
            }

            dataSource.init();
            return dataSource;
        } else {
            throw new IllegalArgumentException("数据链接字符串为空！");
        }
    }

    public static void setDefaultProperty(DruidDataSource dataSource) {
        if (dataSource == null) {
            dataSource = new DruidDataSource();
        }

        dataSource.setTestOnBorrow(false);
        dataSource.setTestOnReturn(false);
        dataSource.setTestWhileIdle(true);
        dataSource.setTimeBetweenEvictionRunsMillis(60000L);
        dataSource.setMinEvictableIdleTimeMillis(25200000L);
        dataSource.setRemoveAbandoned(true);
        dataSource.setRemoveAbandonedTimeout(1800);
        dataSource.setLogAbandoned(true);
    }
}
